package com.audaque.springboot.foshanupload.cloudauthtrans.interceptor;

import cn.hutool.json.JSONUtil;
import com.audaque.springboot.foshanupload.authcore.constants.AuthConst;
import com.audaque.springboot.foshanupload.authcore.model.currentUser.TransmittableThreadLocalCurrentUser;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Base64Utils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author zgb
 * @desc header中的sessionId>redis>TransmittableThreadLocalCurrentUser
 * @date 2023-08-01 17:51:34
 */
@Slf4j
public class AuthHeaderTransInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) {
        log.debug("AuthHeaderTransInterceptor:" + Thread.currentThread().getName());

        String url0 = request.getRequestURI();
        String url1 = request.getContextPath();
        log.debug("完整地址：" + url0);
        log.debug("返回当前页面所在的应用的名字：" + url1);
        
        // 获取请求地址
        String url = request.getRequestURI().substring(request.getContextPath().length());
        log.debug("controllerUrl：" + url);

        String header = request.getHeader(AuthConst.FROM_GATEWAY_CURRENTUSER_HEADER_KEY);
        if(StringUtils.isNotBlank(header)){
            String transmittableThreadLocalCurrentUserStr = new String(Base64Utils.decode(header.getBytes()));
            TransmittableThreadLocalCurrentUser transmittableThreadLocalCurrentUser = JSONUtil.toBean(transmittableThreadLocalCurrentUserStr, TransmittableThreadLocalCurrentUser.class);
            TransmittableThreadLocalCurrentUser.setCurrentUser(transmittableThreadLocalCurrentUser);
        }

        return true;
    }


}
